package com.weibo.basic.alg.alert.server.controller;

import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.weibo.basic.alg.alert.common.entity.JsonReturn;
import com.weibo.basic.alg.alert.server.config.AlarmConfig;
import com.weibo.basic.alg.alert.server.config.Constants;
import io.swagger.annotations.ApiOperation;
import java.util.ArrayList;
import java.util.Arrays;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(Constants.PATH_PREFIX + "/alarmUsers/")
@Slf4j
public class AlarmUsersController {

    @Autowired
    private AlarmConfig alarmConfig;

    @RequestMapping(value = "/", method = RequestMethod.PUT)
    @ApiOperation("添加通知用户")
    public JsonReturn<String> put(@RequestParam("token") String key,
        @RequestParam("users") String users) {
        if (Strings.isNullOrEmpty(key) || !Constants.ADMIN_TOKEN.equals(key)) {
            return JsonReturn.returnFailed("token is empty or invalid");
        }
        alarmConfig.getAlarmUsers().addAll(Arrays.asList(users.split(",")));
        return JsonReturn.returnSuccess(Joiner.on(",").join(alarmConfig.getAlarmUsers()));
    }

    @RequestMapping(value = "/", method = RequestMethod.POST)
    @ApiOperation("替换通知用户(注意:是完全覆盖,不是新增)")
    public JsonReturn<String> post(@RequestParam("token") String key,
        @RequestBody String users) {
        if (Strings.isNullOrEmpty(key) || !Constants.ADMIN_TOKEN.equals(key)) {
            return JsonReturn.returnFailed("token is empty or invalid");
        }
        if (Strings.isNullOrEmpty(users)) {
            return JsonReturn.returnFailed("users cannot be empty");
        }
        alarmConfig.setAlarmUsers(new ArrayList<>(Arrays.asList(users.split(","))));
        return JsonReturn.returnSuccess(Joiner.on(",").join(alarmConfig.getAlarmUsers()));
    }

    @RequestMapping(value = "/", method = RequestMethod.GET)
    @ApiOperation("获取通知用户")
    public JsonReturn<String> get(@RequestParam("token") String key) {
        if (Strings.isNullOrEmpty(key) || !Constants.ADMIN_TOKEN.equals(key)) {
            return JsonReturn.returnFailed("token is empty or invalid");
        }
        return JsonReturn.returnSuccess(Joiner.on(",").join(alarmConfig.getAlarmUsers()));
    }
}
